package org.jeecg.modules.dinguser.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.api.ding.DingApi;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.ComSysUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.dinguser.entity.DiyDingUser;
import org.jeecg.modules.dinguser.mapper.DiyDingUserMapper;
import org.jeecg.modules.dinguser.service.IDiyDingUserService;
import org.jeecg.modules.mapper.DiyProfessorInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: 自定义钉钉用户
 * @Author: jeecg-boot
 * @Date:   2020-05-29
 * @Version: V1.0
 */
@Service
public class DiyDingUserServiceImpl extends ServiceImpl<DiyDingUserMapper, DiyDingUser> implements IDiyDingUserService {

    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private DiyDingUserMapper diyDingUserMapper;

    @Autowired
    private DingApi dingApi;

    @Autowired
    private DiyProfessorInfoMapper diyProfessorInfoMapper;


    @Override
    public void removeDingUserId(String userId) {
        QueryWrapper<DiyDingUser> wrapper = new QueryWrapper<DiyDingUser>().eq("ding_user_id", userId);

        diyDingUserMapper.delete(wrapper);
    }

    @Override
    public void toSaveDingUserInfo(String userId) {
        // 根据userid获取unionid
        String unionId = dingApi.getUnionIdByUserId(userId);
        // 创建登录专家库的账号用户名，离职会删除
        createSysUser(unionId,userId);
    }

    public void createSysUser(String unionId,String userId) {
        // 注册登录账号信息
        ComSysUser user = new ComSysUser();
        String avatar = null;
        String source = "dingtalk";
        // 根据userId获取真实姓名realName
        String username = "thirdLogin";
        user.setActivitiSync(CommonConstant.ACT_SYNC_0);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        user.setStatus(1);
        user.setThirdId(userId);
        user.setThirdType(source);
        user.setAvatar(avatar);
        user.setUsername(unionId);
        user.setRealname(username);

        //设置初始密码
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), "123456", salt);
        user.setPassword(passwordEncode);

        sysBaseAPI.saveThirdUser(user);
    }
}
